package com.hc.springsecurity;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hc.domain.Permission;
import com.hc.domain.Role;
import com.hc.domain.UserPermission;
import com.hc.service.PermissionService;
import com.hc.service.RoleService;
import com.hc.service.UserPermissionService;
import com.hc.service.UserService;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author hc
 * @date 2022/1/615:29
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @Resource
    private UserPermissionService userPermissionService;

    @Resource
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库中读取到的用户名
        com.hc.domain.User userDB = userService.getOne(new QueryWrapper<com.hc.domain.User>()
                .select("id,username,password", "role_id")
                .eq("status", 1)
                .eq("username", username));
        if (userDB == null) {
            throw new UsernameNotFoundException("指定名称的用户不存在");
        }
        //从tb_role和tb_permision表中读取信息
        String temp = "";
        //"ROLE_vip,ROLE_abc,spu:delete,spu:update,spu:selectById";
        //获取当登录用户拥有的角色
        Role role = roleService.getOne(new QueryWrapper<Role>()
                .select("name")
                .eq("status", 1)
                .eq("id", userDB.getRoleId()));
        temp += "ROLE_" + role.getName();
        //获取当前登录用户拥有的权限
        List<UserPermission> userPermissionList = userPermissionService.list(new QueryWrapper<UserPermission>()
                .select("permission_id")
                .eq("user_id", userDB.getId())
                .eq("status", 1));
        for (UserPermission userPermission : userPermissionList) {
            Permission permission = permissionService.getOne(new QueryWrapper<Permission>()
                    .select("name")
                    .eq("status", 1)
                    .eq("id", userPermission.getPermissionId()));
            temp +=","+permission.getName();
        }

        User user = new User(username,
                userDB.getPassword(),
                AuthorityUtils.commaSeparatedStringToAuthorityList(temp)
        );
        return user;
    }

}
